package problem227;

import java.util.Stack;

//227.基本计算器2
//https://leetcode.cn/problems/basic-calculator-ii/

class Solution {
    public int calculate(String s) {
        s = s.trim();
        Stack<Integer> nums = new Stack<>();
        char op = '+';
        int i = 0;
        while(i < s.length()) {
            if(i < s.length() && s.charAt(i) == ' ') i++;
            if(s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                int j = i;
                while(j < s.length() && s.charAt(j) >= '0' && s.charAt(j) <= '9') {
                    j++;
                }
                String str = s.substring(i, j);
                int tmp = Integer.valueOf(str);
                if(op == '+') nums.push(tmp);
                else if(op == '-') nums.push(-tmp);
                else if(op == '*') nums.push(nums.pop() * tmp);
                else if(op == '/') nums.push(nums.pop() / tmp);
                i = j;
            }else {
                op = s.charAt(i);
                i++;
            }
        }
        int ret = 0;
        while(!nums.isEmpty()) {
            ret += nums.pop();
        }
        return ret;
    }
}